package com.lancoo.znbkxx.teacher.widget

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.PopupWindow
import android.widget.RadioButton
import com.bigkoo.pickerview.adapter.ArrayWheelAdapter
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.model.data.TImePickerMin
import com.lancoo.znbkxx.teacher.model.data.TimePickerDate
import com.lancoo.znbkxx.teacher.model.data.TimePickerHour
import kotlinx.android.synthetic.main.view_edit_answer_time.view.*
import java.text.DateFormatSymbols
import java.text.SimpleDateFormat
import java.util.*

/**
 * Created by wealive on 2021/3/5.
 *
 *
 */
@SuppressLint("SetTextI18n")
class AnswerTimeEditPopupWindow(
    val context: Context, val startDate: String, val endDate: String,
    private val onClickListener: View.OnClickListener
) : PopupWindow() {
    private lateinit var dateAdapter: ArrayWheelAdapter<TimePickerDate>
    private lateinit var hourAdapter: ArrayWheelAdapter<TimePickerHour>
    private lateinit var minuteAdapter: ArrayWheelAdapter<TImePickerMin>
    private val dateList = mutableListOf<TimePickerDate>()
    private val hourList = mutableListOf<TimePickerHour>()
    private val minuteList = mutableListOf<TImePickerMin>()
    var indexDayStart = 0
    var indexHourStart = 0
    var indexMinStart = 0
    var indexDayEnd = 0
    var indexHourEnd = 0
    var indexMinEnd = 0
    lateinit var dateStart: Date
    lateinit var dateEnd: Date

    init {
        val contentView = LayoutInflater.from(context).inflate(R.layout.view_edit_answer_time, null)
        initTimeData(startDate, endDate)
        contentView.apply {
            wheel_day.setCyclic(false)
            wheel_hour.setCyclic(false)
            wheel_min.setCyclic(false)
            wheel_day.adapter = dateAdapter
            wheel_hour.adapter = hourAdapter
            wheel_min.adapter = minuteAdapter
            wheel_day.setTextColorCenter(Color.parseColor("#00afff"))
            wheel_hour.setTextColorCenter(Color.parseColor("#00afff"))
            wheel_min.setTextColorCenter(Color.parseColor("#00afff"))
            wheel_day.setTextSize(15f)
            wheel_hour.setTextSize(15f)
            wheel_min.setTextSize(15f)
            wheel_hour.currentItem = indexHourStart
            wheel_min.currentItem = indexMinStart
            wheel_day.wheel_day.setOnItemSelectedListener {
                if (rb_start.isChecked) {
                    indexDayStart = it
                    showTimeText(indexDayStart, indexHourStart, indexMinStart)
                } else {
                    indexDayEnd = it
                    showTimeText(indexDayEnd, indexHourEnd, indexMinEnd)
                }
            }
            wheel_hour.setOnItemSelectedListener {
                if (rb_start.isChecked) {
                    indexHourStart = it
                    showTimeText(indexDayStart, indexHourStart, indexMinStart)
                } else {
                    indexHourEnd = it
                    showTimeText(indexDayEnd, indexHourEnd, indexMinEnd)
                }
            }
            wheel_min.setOnItemSelectedListener {
                if (rb_start.isChecked) {
                    indexMinStart = it
                    showTimeText(indexDayStart, indexHourStart, indexMinStart)
                } else {
                    indexMinEnd = it
                    showTimeText(indexDayEnd, indexHourEnd, indexMinEnd)
                }
            }
            rb_start.text = "开始时间\n${
                dateList[indexDayStart].pickerViewText.let {
                    it.substring(0, it.lastIndexOf("周"))
                }
            } ${hourList[indexHourStart].pickerViewText}${minuteList[indexMinStart].pickerViewText}"
            rb_end.text = "结束时间\n${
                dateList[indexDayEnd].pickerViewText.let {
                    it.substring(0, it.lastIndexOf("周"))
                }
            } ${hourList[indexHourEnd].pickerViewText}${minuteList[indexMinEnd].pickerViewText}"
            val today = Calendar.getInstance()
            if (today.timeInMillis > dateStart.time) {
                rb_start.isEnabled = false
                (rg_time.getChildAt(1) as RadioButton).isChecked = true
            }
            rg_time.setOnCheckedChangeListener { _, checkedId ->
                when (checkedId) {
                    R.id.rb_start -> {
                        wheel_day.currentItem = indexDayStart
                        wheel_hour.currentItem = indexHourStart
                        wheel_min.currentItem = indexMinStart
                    }
                    R.id.rb_end -> {
                        wheel_day.currentItem = indexDayEnd
                        wheel_hour.currentItem = indexHourEnd
                        wheel_min.currentItem = indexMinEnd
                    }
                }
            }
            tv_confirm.setOnClickListener(onClickListener)
            iv_close.setOnClickListener(onClickListener)
        }
        this.contentView = contentView
        animationStyle = R.style.PopupWindow
        this.width = WindowManager.LayoutParams.MATCH_PARENT
        this.height = WindowManager.LayoutParams.WRAP_CONTENT
        this.isOutsideTouchable = false
        this.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        this.isFocusable = true
        update()
    }

    private fun initTimeData(startDate: String, endDate: String) {
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm")
        dateStart = sdf.parse(startDate)
        dateEnd = sdf.parse(endDate)
        val dateTimeStart = Calendar.getInstance().apply { time = dateStart }
        indexHourStart = dateTimeStart.get(Calendar.HOUR_OF_DAY)
        indexMinStart = dateTimeStart.get(Calendar.MINUTE)
        val dateTimeEnd = Calendar.getInstance().apply { time = dateEnd }
        indexDayEnd =
            dateTimeEnd.get(Calendar.DAY_OF_YEAR) - dateTimeStart.get(Calendar.DAY_OF_YEAR)
        indexHourEnd = dateTimeEnd.get(Calendar.HOUR_OF_DAY)
        indexMinEnd = dateTimeEnd.get(Calendar.MINUTE)
        for (i in 0..365) {
            val timeStart = Calendar.getInstance().apply { time = dateStart }
            timeStart.add(Calendar.DAY_OF_YEAR, i)
            timeStart.set(Calendar.HOUR, 0)
            timeStart.set(Calendar.MINUTE, 0)
            timeStart.set(Calendar.SECOND, 0)
            val datePicker = TimePickerDate(
                timeStart.get(Calendar.YEAR),
                timeStart.get(Calendar.MONTH), timeStart.get(Calendar.DAY_OF_MONTH),
                DateFormatSymbols().shortWeekdays[timeStart.get(
                    Calendar.DAY_OF_WEEK
                )]
            )
            dateList.add(datePicker)
        }
        dateAdapter = ArrayWheelAdapter(dateList)
        for (i in 0..23) {
            val datePicker = TimePickerHour(i)
            hourList.add(datePicker)
        }
        hourAdapter = ArrayWheelAdapter(hourList)
        for (i in 0..59) {
            val datePicker = TImePickerMin(i)
            minuteList.add(datePicker)
        }
        minuteAdapter = ArrayWheelAdapter(minuteList)
    }

    private fun showTimeText(indexDay: Int, indexHour: Int, indexMin: Int) {
        val timeText = "${
            dateList[indexDay].pickerViewText.let {
                it.substring(0, it.lastIndexOf("周"))
            }
        } ${hourList[indexHour].pickerViewText}${minuteList[indexMin].pickerViewText}"
        if (contentView.rb_start.isChecked) {
            contentView.rb_start.text = "开始时间\n${timeText}"
        } else {
            contentView.rb_end.text = "结束时间\n${timeText}"
        }
    }

    fun getStartTime(): String {
        val day = dateList[indexDayStart]
        val hour = hourList[indexHourStart]
        val min = minuteList[indexMinStart]
        val time = Calendar.getInstance()
        time.set(day.year, day.month, day.date, hour.hour, min.min)
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        return sdf.format(time.time)
    }

    fun getEndTime(): String {
        val day = dateList[indexDayEnd]
        val hour = hourList[indexHourEnd]
        val min = minuteList[indexMinEnd]
        val time = Calendar.getInstance()
        time.set(day.year, day.month, day.date, hour.hour, min.min)
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        return sdf.format(time.time)
    }
}